<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>参数分组管理</span>
        </div>
      </template>
      
      <el-row :gutter="20">
        <!-- 分组列表 -->
        <el-col :span="8">
          <el-card shadow="never">
            <template #header>
              <div class="group-header">
                <span>分组列表</span>
                <el-button type="primary" size="small" @click="handleAddGroup">添加分组</el-button>
              </div>
            </template>
            
            <el-table 
              v-loading="loading" 
              :data="groupList" 
              style="width: 100%"
              highlight-current-row
              @row-click="handleSelectGroup"
            >
              <el-table-column prop="name" label="分组名称" show-overflow-tooltip />
              <el-table-column prop="count" label="参数数量" width="100" align="center" />
              <el-table-column label="操作" width="120" align="center">
                <template #default="scope">
                  <el-button type="primary" link :icon="Edit" @click.stop="handleEditGroup(scope.row)">编辑</el-button>
                  <el-button 
                    type="danger" 
                    link 
                    :icon="Delete" 
                    @click.stop="handleDeleteGroup(scope.row)"
                    :disabled="scope.row.count > 0"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        
        <!-- 参数列表 -->
        <el-col :span="16">
          <el-card shadow="never">
            <template #header>
              <div class="group-header">
                <span>{{ currentGroup ? `${currentGroup.name}参数` : '参数列表' }}</span>
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="handleAddSetting" 
                  :disabled="!currentGroup"
                >添加参数</el-button>
              </div>
            </template>
            
            <el-table 
              v-loading="settingLoading" 
              :data="settingList" 
              style="width: 100%"
            >
              <el-table-column prop="key" label="参数键名" width="180" show-overflow-tooltip />
              <el-table-column prop="name" label="参数名称" width="150" show-overflow-tooltip />
              <el-table-column prop="value" label="参数值" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.type === 3">{{ scope.row.value ? '是' : '否' }}</span>
                  <span v-else-if="scope.row.type === 4">[数组]</span>
                  <span v-else-if="scope.row.type === 5">{对象}</span>
                  <span v-else>{{ scope.row.value }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="type" label="类型" width="100" align="center">
                <template #default="scope">
                  {{ getSettingTypeLabel(scope.row.type) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" align="center">
                <template #default="scope">
                  <el-button type="primary" link :icon="Edit" @click="handleEditSetting(scope.row)">编辑</el-button>
                  <el-button type="danger" link :icon="Delete" @click="handleDeleteSetting(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页 -->
            <pagination
              v-if="total > 0"
              :total="total"
              v-model:page="queryParams.page"
              v-model:limit="queryParams.limit"
              @pagination="getSettingList"
            />
          </el-card>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 分组对话框 -->
    <el-dialog :title="groupDialog.title" v-model="groupDialog.visible" width="500px" append-to-body>
      <el-form ref="groupFormRef" :model="groupForm" :rules="groupRules" label-width="100px">
        <el-form-item label="分组名称" prop="name">
          <el-input v-model="groupForm.name" placeholder="请输入分组名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitGroupForm">确 定</el-button>
          <el-button @click="groupDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 参数设置对话框 -->
    <el-dialog :title="settingDialog.title" v-model="settingDialog.visible" width="600px" append-to-body>
      <el-form ref="settingFormRef" :model="settingForm" :rules="settingRules" label-width="100px">
        <el-form-item label="参数分组" prop="group">
          <el-select v-model="settingForm.group" placeholder="请选择参数分组" style="width: 100%">
            <el-option 
              v-for="group in groupList" 
              :key="group.name" 
              :label="group.name" 
              :value="group.name" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="参数键名" prop="key">
          <el-input v-model="settingForm.key" placeholder="请输入参数键名" :disabled="settingForm.id" />
        </el-form-item>
        <el-form-item label="参数名称" prop="name">
          <el-input v-model="settingForm.name" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item label="参数类型" prop="type">
          <el-select v-model="settingForm.type" placeholder="请选择参数类型" style="width: 100%">
            <el-option 
              v-for="type in settingTypeOptions" 
              :key="type.value" 
              :label="type.label" 
              :value="type.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="参数值" prop="value">
          <!-- 文本类型 -->
          <el-input 
            v-if="settingForm.type === 1" 
            v-model="settingForm.value" 
            placeholder="请输入参数值" 
          />
          
          <!-- 数字类型 -->
          <el-input-number 
            v-else-if="settingForm.type === 2" 
            v-model.number="settingForm.value" 
            placeholder="请输入参数值" 
            style="width: 100%"
          />
          
          <!-- 布尔类型 -->
          <el-switch 
            v-else-if="settingForm.type === 3" 
            v-model="settingForm.value" 
            :active-value="true"
            :inactive-value="false"
          />
          
          <!-- 数组类型 -->
          <el-input 
            v-else-if="settingForm.type === 4" 
            v-model="settingForm.value" 
            type="textarea" 
            :rows="5" 
            placeholder='请输入JSON数组格式的参数值，例如: ["value1", "value2"]' 
          />
          
          <!-- 对象类型 -->
          <el-input 
            v-else-if="settingForm.type === 5" 
            v-model="settingForm.value" 
            type="textarea" 
            :rows="5" 
            placeholder='请输入JSON对象格式的参数值，例如: {"key1": "value1"}' 
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="settingForm.sort" :min="0" :max="999" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="settingForm.description" type="textarea" :rows="3" placeholder="请输入参数描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSettingForm">确 定</el-button>
          <el-button @click="settingDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete } from '@element-plus/icons-vue'
import { 
  getSettingGroups, 
  getSettingList, 
  getSettingDetail, 
  createSetting, 
  updateSetting, 
  deleteSetting,
  getSettingTypeOptions
} from '@/api/setting'
import Pagination from '@/components/Pagination/index.vue'

// 分组列表
const groupList = ref([])
const loading = ref(false)
const currentGroup = ref(null)

// 参数列表
const settingList = ref([])
const settingLoading = ref(false)
const total = ref(0)
const queryParams = reactive({
  page: 1,
  limit: 10,
  group: ''
})

// 参数类型选项
const settingTypeOptions = getSettingTypeOptions()

// 分组表单
const groupFormRef = ref(null)
const groupForm = reactive({
  name: ''
})
const groupRules = {
  name: [
    { required: true, message: '分组名称不能为空', trigger: 'blur' }
  ]
}
const groupDialog = reactive({
  title: '',
  visible: false,
  isEdit: false
})

// 参数表单
const settingFormRef = ref(null)
const settingForm = reactive({
  id: null,
  key: '',
  name: '',
  value: '',
  group: '',
  type: 1,
  description: '',
  sort: 0
})
const settingRules = {
  key: [
    { required: true, message: '参数键名不能为空', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '参数名称不能为空', trigger: 'blur' }
  ],
  group: [
    { required: true, message: '参数分组不能为空', trigger: 'change' }
  ],
  type: [
    { required: true, message: '参数类型不能为空', trigger: 'change' }
  ],
  value: [
    { 
      validator: (rule, value, callback) => {
        if (settingForm.type === 4) {
          try {
            if (value) {
              JSON.parse(value)
            }
            callback()
          } catch (error) {
            callback(new Error('请输入有效的JSON数组格式'))
          }
        } else if (settingForm.type === 5) {
          try {
            if (value) {
              JSON.parse(value)
            }
            callback()
          } catch (error) {
            callback(new Error('请输入有效的JSON对象格式'))
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
const settingDialog = reactive({
  title: '',
  visible: false,
  isEdit: false
})

// 获取设置类型标签
const getSettingTypeLabel = (type) => {
  const option = settingTypeOptions.find(item => item.value === type)
  return option ? option.label : '未知'
}

// 获取分组列表
const getGroupList = async () => {
  loading.value = true
  try {
    const res = await getSettingGroups()
    const groups = res.data || []
    
    // 获取每个分组的参数数量
    const groupsWithCount = await Promise.all(groups.map(async (group) => {
      const countRes = await getSettingList({ group, page: 1, limit: 1 })
      return {
        name: group,
        count: countRes.data.total || 0
      }
    }))
    
    groupList.value = groupsWithCount
  } catch (error) {
    console.error('获取分组列表失败:', error)
    ElMessage.error('获取分组列表失败')
  } finally {
    loading.value = false
  }
}

// 获取参数列表
const getSettingList = async () => {
  if (!queryParams.group) return
  
  settingLoading.value = true
  try {
    const res = await getSettingList(queryParams)
    settingList.value = res.data.list || []
    total.value = res.data.total || 0
  } catch (error) {
    console.error('获取参数列表失败:', error)
    ElMessage.error('获取参数列表失败')
  } finally {
    settingLoading.value = false
  }
}

// 选择分组
const handleSelectGroup = (row) => {
  currentGroup.value = row
  queryParams.group = row.name
  queryParams.page = 1
  getSettingList()
}

// 添加分组
const handleAddGroup = () => {
  groupDialog.title = '添加分组'
  groupDialog.isEdit = false
  groupDialog.visible = true
  
  groupForm.name = ''
}

// 编辑分组
const handleEditGroup = (row) => {
  groupDialog.title = '编辑分组'
  groupDialog.isEdit = true
  groupDialog.visible = true
  
  groupForm.name = row.name
  groupDialog.oldName = row.name // 保存原名称以便更新
}

// 删除分组
const handleDeleteGroup = (row) => {
  if (row.count > 0) {
    ElMessage.warning('该分组下有参数，无法删除')
    return
  }
  
  ElMessageBox.confirm(`确认删除分组"${row.name}"吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 此处应调用后端删除分组的接口，示例中假设成功
      ElMessage.success('删除分组成功')
      getGroupList()
      
      // 如果删除的是当前选中的分组，则清空选择
      if (currentGroup.value && currentGroup.value.name === row.name) {
        currentGroup.value = null
        queryParams.group = ''
        settingList.value = []
        total.value = 0
      }
    } catch (error) {
      console.error('删除分组失败:', error)
      ElMessage.error('删除分组失败')
    }
  })
}

// 提交分组表单
const submitGroupForm = () => {
  groupFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 此处应调用后端创建/更新分组的接口，示例中假设成功
        if (groupDialog.isEdit) {
          // 更新参数中的分组名
          if (settingList.value.length > 0 && groupDialog.oldName) {
            // 此处应调用后端批量更新参数分组的接口，示例中假设成功
          }
          
          ElMessage.success('更新分组成功')
        } else {
          ElMessage.success('创建分组成功')
        }
        
        groupDialog.visible = false
        getGroupList()
      } catch (error) {
        console.error(groupDialog.isEdit ? '更新分组失败:' : '创建分组失败:', error)
        ElMessage.error(groupDialog.isEdit ? '更新分组失败' : '创建分组失败')
      }
    }
  })
}

// 添加参数
const handleAddSetting = () => {
  settingDialog.title = '添加参数'
  settingDialog.isEdit = false
  settingDialog.visible = true
  
  Object.assign(settingForm, {
    id: null,
    key: '',
    name: '',
    value: '',
    group: currentGroup.value ? currentGroup.value.name : '',
    type: 1,
    description: '',
    sort: 0
  })
}

// 编辑参数
const handleEditSetting = async (row) => {
  settingDialog.title = '编辑参数'
  settingDialog.isEdit = true
  settingDialog.visible = true
  settingLoading.value = true
  
  try {
    const res = await getSettingDetail(row.id)
    const data = res.data
    
    if (data) {
      Object.assign(settingForm, {
        id: data.id,
        key: data.key,
        name: data.name,
        value: data.value,
        group: data.group,
        type: data.type,
        description: data.description,
        sort: data.sort
      })
      
      // 特殊处理不同类型的值
      if (data.type === 3) { // 布尔
        settingForm.value = data.value === 'true' || data.value === true
      } else if (data.type === 4 || data.type === 5) { // 数组或对象
        if (typeof data.value === 'string') {
          try {
            // 格式化JSON字符串以便编辑
            const parsed = JSON.parse(data.value)
            settingForm.value = JSON.stringify(parsed, null, 2)
          } catch (error) {
            // 解析失败，保持原样
          }
        }
      }
    }
  } catch (error) {
    console.error('获取参数详情失败:', error)
    ElMessage.error('获取参数详情失败')
  } finally {
    settingLoading.value = false
  }
}

// 删除参数
const handleDeleteSetting = (row) => {
  ElMessageBox.confirm(`确认删除参数"${row.name}"吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteSetting(row.id)
      ElMessage.success('删除参数成功')
      getSettingList()
      // 更新分组参数数量
      getGroupList()
    } catch (error) {
      console.error('删除参数失败:', error)
      ElMessage.error('删除参数失败')
    }
  })
}

// 提交参数表单
const submitSettingForm = () => {
  settingFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 处理不同类型的值
        let value = settingForm.value
        if (settingForm.type === 4 || settingForm.type === 5) {
          if (value) {
            value = JSON.stringify(JSON.parse(value))
          }
        }
        
        const data = {
          ...settingForm,
          value
        }
        
        if (settingDialog.isEdit) {
          await updateSetting(settingForm.id, data)
          ElMessage.success('更新参数成功')
        } else {
          await createSetting(data)
          ElMessage.success('创建参数成功')
        }
        
        settingDialog.visible = false
        getSettingList()
        // 更新分组参数数量
        getGroupList()
      } catch (error) {
        console.error(settingDialog.isEdit ? '更新参数失败:' : '创建参数失败:', error)
        ElMessage.error(settingDialog.isEdit ? '更新参数失败' : '创建参数失败')
      }
    }
  })
}

onMounted(() => {
  getGroupList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.group-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 